/**
 * Created by Freeman on 2016/6/29.
 */
"use strict";

import * as types from './types'
import api from '../api'
import {setCookie,signOut} from '../utils/authService'


export const showMsg =  ({dispatch},content,type='error') =>{
    dispatch(types.SHOW_MSG,{content:content,type:type})
}

export const hideMsg = ({dispatch}) =>{
    dispatch(types.HIDE_MSG)
}

export const changeStyleMode = ({dispatch}) =>{
    dispatch(types.CHANGE_STYLE_MODE)
}

export const localLogin = (store,userInfo) =>{
    api.localLogin(userInfo).then(response => {

        if (!response.ok){
            //TODO 刷新验证码
            return showMsg(store,response.data.error_msg || '登录失败')
        }
        const token = response.data.token
        setCookie('token',token)
        getUserInfo(store)
        store.dispatch(types.LOGIN_SUCCESS,{token:token})
        showMsg(store,'登录成功，欢迎光临','success')
        store.router.go({path:'/'})
    },response =>{
        //TODO 刷新验证码
        showMsg(store,response.data.error_msg || '登录失败')
    })
}

export const getUserInfo = ({dispatch}) => {
    api.getMe().then(response =>{
        if (!response.ok){
            return dispatch(types.USERINFO_FAILURE)
        }
        dispatch(types.USERINFO_SUCCESS,{user:response.data})
    },response =>{
        dispatch(types.USERINFO_FAILURE)
    })
}

export const updateUser = (store,userInfo) =>{
    api.mdUser(userInfo).then(response =>{
        if(!response.ok){
            return showMsg(store,'更新用户资料失败!')
        }
        store.dispatch(types.UPDATE_USER_SUCCESS, { user: response.data.data })
        showMsg(store,'更新资料成功!','success')
    },response =>{
        showMsg(store,'更新用户资料失败!')
    })
}

export const logout = ({dispatch,router}) =>{
    signOut()
    router.go({path:'/'})
    dispatch(types.LOGOUT_SUCCESS)
}

export const register = (store,userInfo) => {
    api.register(userInfo).then(response => {

        if (!response.ok){
            return showMsg(store,response.data.error_msg || ' 注册失败')
        }
        showMsg(store,'注册成功','success')
        store.router.go({path:'/login'})
    },response =>{
        showMsg(store,response.data.error_msg || '注册失败')
    })
}

//****===================tag action start=======================****//

export const getTagList = ({dispatch}) => {
    api.getTagList().then(response =>{
        if (!response.ok){
            dispatch(types.GET_TAG_LIST_FAILURE)
        }
        dispatch(types.GET_TAG_LIST_SUCCESS,{tagList:response.data.data})
    },response =>{
        dispatch(types.GET_TAG_LIST_FAILURE)
    })
}

//****===================tag action end  =======================****//

//****===================Article action start=======================****//
export const getArticleList = ({dispatch},options,isAdd) =>{
    dispatch(types.REQUEST_ARTICLE_LIST)
    api.getArticleList(options).then(response =>{
        if(!response.ok){
            return dispatch(types.GET_ARTICLE_LIST_FAILURE)
        }
        const json = response.data
        const isMore = !(json.data.length < options.pageSize)
        isAdd ?
            dispatch(types.ADD_ARTICLE_LIST,{
                articleList: json.data,
                isMore:isMore
            })
            :
            dispatch(types.GET_ARTICLE_LIST_SUCCESS,{
            articleList: json.data,
            isMore:isMore
        })
    },response =>{
        dispatch(types.GET_ARTICLE_LIST_FAILURE)
    })
}

export const getArticleDetail = ({dispatch},id,user) =>{
    api.getFrontArticle(id).then(response =>{
        if (response.ok){
            let isLike = false
            let article = response.data.data
            if (user){
                user.likes.map(item =>{
                    if (item.toString() == article._id){
                        isLike = true
                    }
                })
            }
            dispatch(types.GET_ARTICLE_DETAIL_SUCCESS,{
                articleDetail: {...article,...isLike}
            })
        }
    },response=>{

    })
}
export const toggleLike = ({dispatch},id) =>{
    api.toggleLike(id).then(response =>{
        const json = response.data
        if(response.ok){
            dispatch(types.TOGGLE_LIKE, {
                like_count: json.count,
                isLike: json.isLike
            })
        }
    },response =>{

    })
}
//****===================Article action end  =======================****//

//****===================options action start=======================****//

export const changeOptions = ({dispatch},options) => {
    dispatch(types.CHANGE_OPTIONS,{options:options})
}
//****===================options action end  =======================****//

//****===================options action start=======================****//

export const getCommentList = ({dispatch},id) => {

    api.getFrontCommentList(id).then(response =>{
        if (!response.ok){
            dispatch(types.GET_COMMENT_LIST_FAILURE)
        }
        dispatch(types.GET_COMMENT_LIST_SUCCESS,{commentList:response.data.data})
    },response =>{
        dispatch(types.GET_COMMENT_LIST_FAILURE)
    })
}

export const addComment = (store,data) => {
    api.addNewComment(data).then(response =>{
        if (!response.ok){
            return showMsg(store,response.data.error_msg || '添加评论失败')
        }
        showMsg(store,'添加评论成功','success')
        store.dispatch(types.ADD_COMMENT_SUCCESS,{comment:response.data.data})
    },response =>{
        showMsg(store,response.data.error_msg || '添加评论失败!')
    })
}

export const addReply = (store,cid,data) =>{
    api.addNewReply(cid,data).then(response =>{
        if (!response.ok){
            return showMsg(store,response.data.error_msg || '添加评论失败')
        }
        showMsg(store,'添加评论成功','success')
        store.dispatch(types.ADD_REPLY_SUCCESS,{ cid:cid,replys: response.data.data })
    },response =>{
        showMsg(store,response.data.error_msg || '添加评论失败!')
    })
}
//****===================options action end  =======================****//

//****===================article write action start=======================****//
export const writeArticle = ({dispatch},value) =>{
    dispatch(types.WRITER_UPDATE_ARTICLE,{article:value})
}
export const publishArticle = (store,data) => {
    store.dispatch(types.REQUEST_PUBLISH_ARTICLE)
    api.addNewArticle(data).then(response =>{
        if (!response.ok){
            return showMsg(store,response.data.error_msg || '发表文章失败')
        }
        showMsg(store,'发表文章成功','success')
        store.dispatch(types.PUBLISH_ARTICLE_SUCCESS)
        store.router.go({path:'/'})
    },response =>{
        showMsg(store,response.data.error_msg || '发表文章失败!')
        store.dispatch(types.PUBLISH_ARTICLE_FAILURE)
    })
}

export const deleteArticleAction = (store,id) =>{
    api.deleteArticle(id).then(response =>{
        if (!response.ok){
            return showMsg(store,response.data.error_msg || '删除文章失败')
        }
        showMsg(store,'删除文章成功','success')
        store.dispatch(types.DELETE_ARTICLE_SUCCESS,{id:id})
    },response =>{
        showMsg(store,response.data.error_msg || '删除文章失败!')
    })
}
//****===================article write action end=======================****//

//****===================article search action start=======================****//
export const clearSearch = ({dispatch})=>{
    dispatch(types.CLEAR_SEARCH)
}
export const handleChangeSearch = ({dispatch},data) =>{
    dispatch(types.CHANGE_SEARCH,data)
}

export const search = ({dispatch},isAdd,option) => {
    //store.dispatch(types.REQUEST_PUBLISH_ARTICLE)
    api.search({q:option.q}).then(response =>{
        if(!response.ok){
            return dispatch(types.REQUEST_SEARCH_FAILURE)
        }
        const json = response.data
        const isMore = !(json.hits.length < option.pageSize)
        isAdd ?
            dispatch(types.ADD_SEARCH_SUCCESS,{
                hits: json.hits,
                isMore:isMore
            })
            :
            dispatch(types.REQUEST_SEARCH_SUCCESS,{
                hits: json.hits,
                isMore:isMore
            })
    },response =>{
        dispatch(types.REQUEST_SEARCH_FAILURE)
    })
}
//****===================article search action end=======================****//